﻿using MailKit.Net.Smtp;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.Extensions.Options;
using MimeKit;
using SageKing.MailKit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SageKing.OpenIddict.UI.Infrastructure.Services;

public class MailKitEmailSender : IEmailSender
{
    private readonly EmailOptions _setting;
    public MailKitEmailSender(IOptions<EmailOptions> settings) => _setting = settings.Value;

    public async Task SendEmailAsync(string toEmail, string subject, string htmlMessage)
    {
        //是否开启
        if (!_setting.Enable) return;

        using var client = new SmtpClient();

        var message = new MimeMessage();
        message.From.Add(new MailboxAddress(_setting.SenderName, _setting.SenderEmail));
        message.To.Add(new MailboxAddress("To:", toEmail));
        message.Subject = subject;

        // 纯文本邮件
        //message.Body = new TextPart("plain") { Text = "Hello, this is a test." };

        // HTML 邮件（支持富文本）
        var bodyBuilder = new BodyBuilder();
        //bodyBuilder.HtmlBody = "<h1>Hello</h1><p>This is <b>HTML</b> content.</p>";
        bodyBuilder.HtmlBody = htmlMessage;
        message.Body = bodyBuilder.ToMessageBody();

        // 忽略证书错误（测试环境）
        client.ServerCertificateValidationCallback = (s, c, h, e) => true;

        await client.ConnectAsync(_setting.SmtpServer, _setting.Port, true);
        await client.AuthenticateAsync(_setting.UserName, _setting.Password);
        await client.SendAsync(message);
        await client.DisconnectAsync(true);
    }

}
